package com.example.administrator.yuejian35;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;

import com.example.administrator.yuejian35.Login.LoginFragment;
import com.example.administrator.yuejian35.base.BaseActivity;

public class MainActivity extends BaseActivity {

    private FragmentManager fragmentManager;
    private FragmentTransaction transaction;

    private LoginFragment loginFragment;
    private MainFragment mainFragment;

    private SharedPreferences sp;
    private SharedPreferences.Editor editor;



    private String userId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sp = getSharedPreferences("User", Context.MODE_PRIVATE);
        //editor=sp.edit();
        fragmentManager = getSupportFragmentManager();
        showMainFragment();
        //判断是否登录,如果登录，进入主界面
        //否则，显示登录界面
        boolean loginState = getLoginState();
        if(loginState){
            //直接进入主页面
            showMainFragment();
            //   userId = readUserId();//读取已存储的用户的Id
        }
        else{
            //显示登录
            showLoginFragment();
        }
    }

    private void showLoginFragment(){
        transaction=fragmentManager.beginTransaction();

        loginFragment=new LoginFragment();
        transaction.add(R.id.fragment_holder,loginFragment);

        transaction.commit();
    }

    private void showMainFragment(){
        transaction=fragmentManager.beginTransaction();

        mainFragment=new MainFragment();
        transaction.add(R.id.fragment_holder,mainFragment);

        transaction.commit();
    }

    public void replaceLoginFragment(){
        mainFragment=new MainFragment();
        transaction=fragmentManager.beginTransaction();
        transaction.replace(R.id.fragment_holder,mainFragment);
        transaction.commit();
    }


    private boolean getLoginState(){
        String userId = sp.getString("user_id", null);
         if(userId!=null){
             setUserId(userId);
             return true;
         }
        else {
             return false;
         }


    }

   /* public String getSavedUserId(){
        sp = getSharedPreferences(fileName,
                mode);
        userId = sp.getString("user_id","-1");//第二个参数   未读到数据时读的数据！
        return userId;
    }

    public void setSavedUserId(String userId){
        sp = getSharedPreferences(fileName,
                mode);
        editor=sp.edit();
        editor.putString("user_id",userId);
        editor.commit();
    }*/

}